weeklySkuAssigned

- 🇬🇧 English
- 🇮🇹 Italiano
Function Names: weeklySkuAssigned / testWeeklySkuAssigned
Author: Domenico Cerone Creation Date: 25/09/2025
Last Reviewer: Domenico Cerone
Trigger: Scheduler (onSchedule - every Friday at 18:00) / HTTPS (onRequest)
Purpose: Sends weekly notifications to modellers with the list of SKUs that have been assigned to them during the week.
Detailed Functionality
This Firebase Function performs the following operations in sequence:
1. Supervisor Retrieval
- Queries the
Profilescollection to get all users withModellerSupervisorrole - Extracts supervisor emails that will be CC'd in notifications
2. Weekly Period Calculation
- Determines the start of the current week (Monday at 00:00:00)
- Properly handles the Sunday case to calculate the previous Monday
3. Assignment Log Analysis
- Retrieves all documents from the
LogVariantcollection - For each log, analyses the
list_variant_assignedarray to find the last assignment - Filters only assignments that occurred in the current week
- Groups SKUs by assigned modeller
4. Data Enrichment
- For each assigned SKU, retrieves data from the
Variantscollection to obtain:mainBrandRefproductRefvariantId
- This data is used to build validation links
5. User Profile Retrieval
- For each modeller, attempts to retrieve the profile from the
Profilescollection - If found, uses
firstNameandlastNamefor the full name - Otherwise, formats the username from the email as fallback
6. NOTIFICATION PREFERENCE CHECK
- NEW FEATURE: Before sending any email, the function checks the recipient's profile for notification preferences
- Check Field:
notification_types.weeklySkuAssignedin the user's profile - Logic: If
notification_types.weeklySkuAssignedisfalse, the email is NOT sent - Default Behavior: If the field is missing or
true, the email is sent normally - Granular Control: Users can enable/disable specific notification types without affecting others
- Profile Field:
notification_typesis a map containing boolean values for each notification type - Example:
notification_types: { weeklySkuAssigned: false }disables this notification
7. Email Preparation and Sending
- Builds an HTML table with assigned SKUs containing:
- SKU
- Product name
- Validation link (format:
http://localhost:3000/framevalidation/{mainBrandRef}/{productRef}/{variantId})
- Uses ZeptoMail with predefined template (
MAIL_TEMPLATE_KEY:13ef.8598f19fbcc5adb.k1.b09af280-4609-11f0-900d-dad70ff08860.1975a4e91a8) - Includes in the template:
countSku: total number of assigned SKUslist: HTML table of SKUsaccountName: modeller's full name
- CCs all ModellerSupervisors
8. Error Handling and Fallbacks
- In case of ZeptoMail error, uses nodemailer as fallback
- Sends a simplified text version of the email
- Records all results (success/error) for each modeller
9. Email Configuration
- Sender: no-reply@arshades.com (ARShades Studio)
- SMTP Server: smtp.zeptomail.eu:587
- Template: ZeptoMail template system for formatted emails
- Time Zone: Europe/Rome for scheduling
10. Scheduling
- Main function: Runs automatically every Friday at 18:00
- Test function: Available as HTTP endpoint for manual testing
- Region: europe-central2
The function ensures that each modeller receives a complete and formatted notification with all SKUs that have been assigned to them during the week, facilitating workload monitoring and priority management.
Input (Payload):
For the scheduled function (weeklySkuAssigned):
No input required - automatically triggered by Firebase Scheduler every Friday at 18:00
For the HTTP test function (testWeeklySkuAssigned):
No payload required - simple GET request without parameters
Output (Success):
For the scheduled function (weeklySkuAssigned):
Output visible only in Cloud Functions Logs on Google Cloud Console
The function returns null but logs results in the format:
"Weekly SKU assignment report completed: [results array]"
For the HTTP test function (testWeeklySkuAssigned):
{
"success": true,
"message": "Weekly SKU assignment report completed successfully",
"results": [
{
"email": "modellatore@arshades.com",
"skuCount": 5,
"success": true
}
]
}
This output is returned in the HTTP response (Postman, browser, curl)
Testing
URL (if HTTPS): http://127.0.0.1:5001/arshadesstaging/us-central1/testWeeklySkuAssigned
Test with Emulator:
- Start the Firebase emulator:
firebase emulators:start --only functions - Ensure you're using Node.js version 20:
nvm use 20 - Test with curl:
curl "http://127.0.0.1:5001/arshadesstaging/us-central1/testWeeklySkuAssigned"
Postman Testing:
- Method: GET
- URL: http://127.0.0.1:5001/arshadesstaging/us-central1/testWeeklySkuAssigned
- Headers: No specific headers required
Deploy Command:
To deploy the scheduled function:
firebase deploy --only functions:weeklySkuAssigned
This is the main function that automatically triggers every Friday at 18:00
To deploy the test function (optional):
firebase deploy --only functions:testWeeklySkuAssigned
This function is used only for testing and is normally not deployed
To deploy both:
firebase deploy --only functions:weeklySkuAssigned,functions:testWeeklySkuAssigned
Production URL:
Live Function (Scheduled): https://europe-central2-arshades-7e18a.cloudfunctions.net/weeklySkuAssigned
Note: This function runs automatically every Friday at 18:00. The URL is for reference only as scheduled functions cannot be called directly.
Function Names: weeklySkuAssigned / testWeeklySkuAssigned
Autore: Domenico Cerone Data di creazione: 25/09/2025
Last Reviewer: Domenico Cerone
Trigger: Scheduler (onSchedule - ogni venerdì alle 18:00) / HTTPS (onRequest)
Purpose: Invia una notifica settimanale ai modellatori con la lista degli SKU che sono stati loro assegnati durante la settimana.
Funzionamento Dettagliato
Questa Firebase Function esegue le seguenti operazioni in sequenza:
1. Recupero dei Supervisori
- Interroga la collezione
Profilesper ottenere tutti gli utenti con ruoloModellerSupervisor - Estrae le email dei supervisori che saranno messe in CC nelle notifiche
2. Calcolo del Periodo Settimanale
- Determina l'inizio della settimana corrente (lunedì alle 00:00:00)
- Gestisce correttamente il caso della domenica per calcolare il lunedì precedente
3. Analisi dei Log di Assegnazione
- Recupera tutti i documenti dalla collezione
LogVariant - Per ogni log, analizza l'array
list_variant_assignedper trovare l'ultima assegnazione - Filtra solo le assegnazioni avvenute nella settimana corrente
- Raggruppa gli SKU per modellatore assegnato
4. Arricchimento dei Dati
- Per ogni SKU assegnato, recupera i dati dalla collezione
Variantsper ottenere:mainBrandRefproductRefvariantId
- Questi dati vengono utilizzati per costruire i link di validazione
5. Recupero Profili Utente
- Per ogni modellatore, tenta di recuperare il profilo dalla collezione
Profiles - Se trovato, utilizza
firstNameelastNameper il nome completo - In caso contrario, formatta l'username dall'email come fallback
6. CONTROLLO PREFERENZE NOTIFICHE
- NUOVA FUNZIONALITÀ: Prima di inviare qualsiasi email, la funzione controlla le preferenze di notifica del destinatario nel suo profilo
- Campo di Controllo:
notification_types.weeklySkuAssignednel profilo dell'utente - Logica: Se
notification_types.weeklySkuAssignedèfalse, l'email NON viene inviata - Comportamento Predefinito: Se il campo è mancante o
true, l'email viene inviata normalmente - Controllo Granulare: Gli utenti possono abilitare/disabilitare tipi specifici di notifica senza influenzare gli altri
- Campo Profilo:
notification_typesè una mappa contenente valori booleani per ogni tipo di notifica - Esempio:
notification_types: { weeklySkuAssigned: false }disabilita questa notifica
7. Preparazione e Invio Email
- Costruisce una tabella HTML con gli SKU assegnati contenente:
- SKU
- Nome del prodotto
- Link di validazione (formato:
http://localhost:3000/framevalidation/{mainBrandRef}/{productRef}/{variantId})
- Utilizza ZeptoMail con template predefinito (
MAIL_TEMPLATE_KEY:13ef.8598f19fbcc5adb.k1.b09af280-4609-11f0-900d-dad70ff08860.1975a4e91a8) - Include nel template:
countSku: numero totale di SKU assegnatilist: tabella HTML degli SKUaccountName: nome completo del modellatore
- Mette in CC tutti i ModellerSupervisor
8. Gestione Errori e Fallback
- In caso di errore con ZeptoMail, utilizza nodemailer come fallback
- Invia una versione testuale semplificata dell'email
- Registra tutti i risultati (successo/errore) per ogni modellatore
9. Configurazione Email
- Mittente: no-reply@arshades.com (ARShades Studio)
- Server SMTP: smtp.zeptomail.eu:587
- Template: Sistema di template ZeptoMail per email formattate
- Fuso Orario: Europe/Rome per la schedulazione
10. Schedulazione
- Funzione principale: Esegue automaticamente ogni venerdì alle 18:00
- Funzione di test: Disponibile come endpoint HTTP per test manuali
- Regione: europe-central2
La funzione garantisce che ogni modellatore riceva una notifica completa e formattata con tutti gli SKU che gli sono stati assegnati durante la settimana, facilitando il monitoraggio del carico di lavoro e la gestione delle priorità.
Input (Payload):
Per la funzione schedulata (weeklySkuAssigned):
Nessun input richiesto - viene attivata automaticamente dal Firebase Scheduler ogni venerdì alle 18:00
Per la funzione di test HTTP (testWeeklySkuAssigned):
Nessun payload richiesto - semplice richiesta GET senza parametri
Output (Success):
Per la funzione schedulata (weeklySkuAssigned):
Output visibile solo nei Cloud Functions Logs su Google Cloud Console
La funzione restituisce null ma logga i risultati nel formato:
"Report settimanale SKU assegnati completato: [array dei risultati]"
Per la funzione di test HTTP (testWeeklySkuAssigned):
{
"success": true,
"message": "Report settimanale SKU assegnati completato con successo",
"results": [
{
"email": "modellatore@arshades.com",
"skuCount": 5,
"success": true
}
]
}
Questo output viene restituito nella risposta HTTP (Postman, browser, curl)
Testing
URL (if HTTPS): http://127.0.0.1:5001/arshadesstaging/us-central1/testWeeklySkuAssigned
Test with Emulator:
- Avviare l'emulatore Firebase:
firebase emulators:start --only functions - Assicurarsi di usare Node.js versione 20:
nvm use 20 - Testare con curl:
curl "http://127.0.0.1:5001/arshadesstaging/us-central1/testWeeklySkuAssigned"
Postman Testing:
- Metodo: GET
- URL: http://127.0.0.1:5001/arshadesstaging/us-central1/testWeeklySkuAssigned
- Headers: Nessun header specifico richiesto
Deploy Command:
Per deployare la funzione schedulata:
firebase deploy --only functions:weeklySkuAssigned
Questa è la funzione principale che si attiva automaticamente ogni venerdì alle 18:00
Per deployare la funzione di test (opzionale):
firebase deploy --only functions:testWeeklySkuAssigned
Questa funzione è utilizzata solo per testing e normalmente non viene deployata
Per deployare entrambe:
firebase deploy --only functions:weeklySkuAssigned,functions:testWeeklySkuAssigned
URL di Produzione:
Funzione Live (Schedulata): https://europe-central2-arshades-7e18a.cloudfunctions.net/weeklySkuAssigned
Nota: Questa funzione viene eseguita automaticamente ogni venerdì alle 18:00. L'URL è solo di riferimento poiché le funzioni schedulte non possono essere chiamate direttamente.